<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="点检项目" prop="ByzxCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入点检项目" clearable size="small" style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="点检状态" prop="byStatus">
        <el-select @keyup.enter.native="handleQuery" v-model="queryParams.byStatus" placeholder="请选择点检状态" clearable
          filterable size="small">
          <el-option v-for="item in byStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentId">
        <el-select v-model="queryParams.equipmentId" placeholder="请选择设备" @change="shebeiChange" clearable filterable
          size="small">
          <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookName" :value="item.bookId" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编码" prop="equipmentCode">
        <el-select v-model="queryParams.equipmentCode" placeholder="请选择设备" @change="shebeibmChange" clearable filterable
          size="small">
          <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookCode" :value="item.bookCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <treeselect v-model="queryParams.equipmentType" :options="equipmentTypeOption" :normalizer="normalizerazSblx"
          style="width: 240px" placeholder="请选择设备类型" />
      </el-form-item>
      <el-form-item label="计划执行日期" prop="planDate" label-width="100px">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="点检时间" prop="byDate" label-width="100px">
        <el-date-picker v-model="dateRange2" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['equipment:inspect:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['equipment:inspect:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ByzxList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="60" align="center" fixed="left" />
      <el-table-column label="点检主键id" align="center" width="100" fixed="left" prop="orderId" v-if="false" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" width="200" fixed="left" />
      <el-table-column label="设备类型" align="center" prop="equipmentType" width="100" />
      <el-table-column label="设备编码" align="center" prop="equipmentCode" width="100" />
      <el-table-column label="点检生成时间" align="center" prop="planDate" width="160" />
      <el-table-column label="点检项目" align="center" prop="byType" width="100" />
      <el-table-column label="点检内容" align="center" prop="byData" width="200" />
      <el-table-column label="点检详情" align="center" prop="byInfo" width="200" />
      <el-table-column label="点检执行时间" align="center" prop="byDate" width="160" />
      <el-table-column label="点检状态" align="center" prop="byStatus" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.byStatus===0?'未点检':scope.row.byStatus===1?'已点检':''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="点检人" align="center" prop="routingCode" width="100" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" style="margin-right: 9px"
            @click="handleUpdate(scope.row)" v-hasPermi="['equipment:inspect:edit']">执行</el-button>

          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:inspect:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备点检对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :lg="12">
            <el-form-item label="设备名称" prop="equipmentId">
              <el-select v-model="form.equipmentId" placeholder="请选择设备" @change="shebeiFormChange" clearable filterable
                size="small">
                <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookName"
                  :value="item.bookId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="设备编码" prop="equipmentCode">
              <el-select v-model="form.equipmentCode" placeholder="请选择设备" @change="shebeibmFormChange" clearable
                filterable size="small">
                <el-option v-for="item in shebeiOptions" :key="item.bookId" :label="item.bookCode"
                  :value="item.bookId" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :lg="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <treeselect v-model="form.equipmentType" :options="equipmentTypeOption" :normalizer="normalizerazSblx"
                placeholder="请选择设备类型" />
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="12">
            <el-form-item label="计划执行日期" prop="planDate">
              <el-date-picker v-model="form.planDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :lg="12">
            <el-form-item label="点检项目" prop="byType">
              <el-input v-model="form.byType" placeholder="请输入点检项目" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="点检内容" prop="byData">
              <el-input v-model="form.byData" placeholder="请输入点检内容" />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="点检详情" prop="byInfo">
              <el-input v-model="form.byInfo" placeholder="请输入点检详情" />
            </el-form-item>
          </el-col>
          <!-- <el-col :lg="12">
            <el-form-item label="点检时间" prop="byDate">
              <el-date-picker v-model="form.byDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择点检时间"></el-date-picker>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :lg="12">
            <el-form-item label="点检图片">
              <el-upload ref="upload" :action="upload.url" list-type="picture-card" accept=".png,.jpg"
                :http-request="httpRequest" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <div class="el-upload__tip" style="color:red">提示：仅允许导入“jpg”“png”格式文件！</div>
              <div v-for="item in upload.uploadFiles" style="position: relative;margin-top: 10px; display: flex;">
                <img style="width: 40%;height: 30%;cursor: pointer;" id="imgBy" :src="item">
                <a href="#" style="position: absolute;left: 27%;top: 5%;color: black;" @click="imgClick(item,'del')">
                  删除</a>
                <a href="#" style=" position: absolute;left: 2%;top: 5%;color: black;" @click="imgClick(item)">预览</a>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    listByzx,
    getByzx,
    delByzx,
    addByzx,
    updateByzx,
    exportByzx,
    delImgs
  } from "@/api/equipment/maintain";
  import { listBill } from "@/api/equipment/bill";
  import { listEquipmentType } from "@/api/equipment/type";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { getToken } from "@/utils/auth";
  import Axios from "axios";
  import config from "../../../../vue.config";
  export default {
    name: "Maintain",
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true, shebeiOptions: [], dateRange: [], dateRange2: [], equipmentTypeOption: [],
        byStatusOptions: [{ value: 0, label: '未点检' }, { value: 1, label: '已点检' }], dialogImageUrl: '',
        dialogVisible: false,
        upload: {
          url: process.env.VUE_APP_BASE_API + "/system/upload/img",
          imgUrls: '', uploadFiles: [], uploadZcFiles: [],
        },
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        ByzxList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          byLx: 2
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          equipmentId: [{ required: true, message: "设备名称不能为空", trigger: "change" }],
          equipmentCode: [{ required: true, message: "设备编码不能为空", trigger: "change" }]
        }
      };
    },
    created() {
      this.getList();
      /* 设备下拉选择 */
      listBill().then((response) => {
        this.shebeiOptions = response.rows;
      });
      /* 设备类型树选择 */
      listEquipmentType().then(res => {
        this.equipmentTypeOption = res.data
      })
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        listByzx(this.addDateRange(this.queryParams, this.dateRange, this.dateRange2)).then(response => {
          this.ByzxList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //param是自带参数。 this.$refs.upload.submit() 会自动调用 httpRequest方法.在里面取得file
      httpRequest(param) {
        this.upload.uploadZcFiles.push(param.file)
      },
      imgClick(data, type) {
        if (type === 'del') {
          const str = data.split('uploadimg')[1]
          console.log('str', str);
          delImgs({ path: [str] }).then(res => {
            if (res.code === 200) {
              this.upload.uploadFiles = this.upload.uploadFiles.filter(item => {
                console.log(' item.includes(str)', item.includes(str));
                if (!item.includes(str)) {
                  return item
                }
              })
              this.msgSuccess('删除成功')
            }
          })
        } else {
          this.dialogImageUrl = data;
          this.dialogVisible = true;
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.upload.uploadZcFiles = []
        const byzxIds = row.byzxId || this.ids;
        getByzx(byzxIds).then(res => {
          this.form = res.data;
          this.open = true;
          this.title = "修改设备点检";
          this.upload.uploadFiles = res.data.imgPath.map(item => {
            // config.devServer.proxy[process.env.VUE_APP_BASE_API].target
            return 'http://192.168.3.40:8089/' + 'uploadimg' + item
          })

        });
      },
      /** 提交按钮 */
      async submitForm() {
        // this.$refs.upload.submit();
        let fd = new FormData()// FormData 对象
        this.upload.uploadZcFiles.forEach(item => {
          return fd.append('file', item)
        })
        let url = process.env.VUE_APP_BASE_API + "/system/upload/img"
        let configs = {
          headers:
            { Authorization: "Bearer " + getToken() }
        }
        Axios.post(url, fd, configs).then(res => {
          if (res.status === 200) {
            // this.msgSuccess(res.data.msg)
            this.$refs["form"].validate(valid => {
              if (valid) {
                this.submitLoading = true
                if (this.title === '修改设备保养') {
                  const uploadAllFiles = this.upload.uploadFiles.map(item => item.split('uploadimg')[1]).concat(res.data.imgUrl)
                  updateByzx({ ...this.form, byLx: 2, imgPath: uploadAllFiles }).then(response => {
                    if (response.code === 200) {
                      this.submitLoading = false
                      this.msgSuccess("修改成功");
                      this.$refs.upload.clearFiles()
                      this.open = false;
                      this.getList();
                    }
                  }).catch(err => { this.submitLoading = false })
                } else {
                  addByzx({ ...this.form, byLx: 2, imgPath: res.data.imgUrl }).then(response => {
                    if (response.code === 200) {
                      this.submitLoading = false
                      this.$refs.upload.clearFiles()
                      this.msgSuccess("新增成功");
                      this.open = false;
                      this.getList();
                    }
                  }).catch(err => { this.submitLoading = false });
                }
                this.submitLoading = false
              }
            });
          }
        })
      },
      //删除图片
      handleRemove(file, fileList) {
        console.log('file', file,);
        console.log('fileList', fileList);

      },
      //预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      shebeiFormChange(val) {
        this.$forceUpdate()
        this.form.equipmentCode = this.shebeiOptions.filter(item => item?.bookId === val)[0]?.bookCode
      },
      shebeibmFormChange(val) {
        this.$forceUpdate()
        this.form.equipmentId = this.shebeiOptions.filter(item => item?.bookId === val)[0]?.bookName
      },
      shebeiChange(val) {
        this.$forceUpdate()
        this.queryParams.equipmentCode = this.shebeiOptions.filter(item => item?.bookId === val)[0]?.bookCode
      },
      shebeibmChange(val) {
        this.$forceUpdate()
        this.queryParams.equipmentId = this.shebeiOptions.filter(item => item?.bookCode === val)[0]?.bookName
      },
      /* 设备类型转换结构 */
      normalizerazSblx(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.typeId,
          label: node.typeName,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
        // this.$refs.upload.clearFiles()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = []
        this.dateRange2 = []

        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.ByzxId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.upload.uploadZcFiles = []
        this.upload.uploadFiles = []
        this.open = true;
        this.title = "添加设备点检";
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const byzxIds = row.byzxId || this.ids;
        this.$confirm('是否确认删除设备点检编号为"' + byzxIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delByzx(byzxIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () { });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有设备点检数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportByzx(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () { });
      }
    }
  };
</script>